const express = require('express')
const path = require('path')
const fs = require('fs')
const md = require('markdown-it')()
const matter = require('gray-matter')
const dayjs = require('dayjs')
const glob = require('glob')

module.exports = (targetDir = '.') => {
  const app = express()

  // view engine setup
  app.engine('html', require('express-art-template'))
  // app.set('view', {
  //   debug: process.env.NODE_ENV !== 'production'
  // })
  app.set('views', path.join(targetDir, '_layout/default'))
  app.set('view engine', 'art')

  // 静态资源
  app.use('/public', express.static(path.join(targetDir, './public')))

  // 渲染文章
  app.get('/posts/*', (req, res, next) => {
    try {
      // path.parse(req.params)
      const pathObj = path.parse(req.params[0])
      const filePath =
        path.join(targetDir, '_posts', pathObj.dir, pathObj.name) + '.md'
      const fileData = fs.readFileSync(filePath)
      const {
        content,
        data: meta,
        excerpt
      } = matter(fileData.toString(), {
        excerpt: true
      })
      meta.date = dayjs(meta.date).format('YYYY-MM-DD HH:mm:ss')
      const html = md.render(content)
      res.render('post.html', {
        meta,
        content: html
      })
      // res.setHeader('Content-Type', 'text/html; charset=utf-8')
      // res.send(md.render(content))
    } catch (err) {
      next(err)
    }
  })

  // 渲染文章列表
  app.get('/', async (req, res, next) => {
    console.log(123)
    try {
      const paths = await glob.sync(path.join(targetDir, '_posts/**/*.md'), {})
      console.log(paths)
      const posts = paths.map(item => {
        const post = {}
        const source = fs.readFileSync(item, 'utf8')
        post.meta = matter(source).data
        const pathObj = path.parse(item.split(`${path.basename(targetDir)}/_posts`)[1])
        post.url =  `posts${pathObj.dir}/${pathObj.name}.html`
        return post
      })
      // res.send('get /posts')
      res.render('index.html', {
        posts
      })
    } catch (err) {
      next()
    }
  })

  app.use((err, req, res, next) => {
    res.status(500).send(err.message)
  })

  app.listen(3000, () => {
    console.log('dev server is started at http://localhost:3000/')
  })
}
